package com.dandandog.framework.common.utils;

import cn.hutool.core.util.ClassUtil;
import com.dandandog.framework.common.config.properties.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * @Author: JohnnyLiu
 * @Date: 2021/11/17 9:45
 */
@Component
@EnableConfigurationProperties(MessageProperties.class)
public class MessageUtil {

    private static MessageSource messageSource;

    @Autowired
    public MessageUtil(MessageSource messageSource) {
        MessageUtil.messageSource = messageSource;
    }

    public static String getMessageSource(String key, Locale locale, Object... detail) {
        return messageSource.getMessage(key, detail, locale);
    }

    public static String getMessageSource(String key, Object... detail) {
        Locale currLocale = LocaleUtil.getCurrLocale();
        return messageSource.getMessage(key, detail, currLocale);
    }


    public static String getMessageEnum(EnumMessage enumeration, Locale locale) {
        return messageSource.getMessage(getMessageEnumKey(enumeration), null, locale);
    }

    public static String getMessageEnum(EnumMessage enumeration) {
        Locale currLocale = LocaleUtil.getCurrLocale();
        return messageSource.getMessage(getMessageEnumKey(enumeration), null, currLocale);
    }

    private static String getMessageEnumKey(EnumMessage enumeration) {
        return ClassUtil.getClassName(enumeration.getClass(), true) + "." + enumeration.name();
    }

}
